import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:mziot/app/data/circle_list_entity.dart';
import 'package:mziot/app/modules/circle/circle_provider.dart';
import 'package:mziot/app/tools/tools.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class CircleController extends GetxController {
  CircleProvider provider = CircleProvider();
  RefreshController controller = RefreshController();
  final images = <String>[].obs;
  final dataList = <CircleListVosList>[].obs;
  var currentNum = 0;
  var hasNext = true;

  @override
  void onInit() {
    super.onInit();

    fetchList();
  }

  void refreshData() {
    currentNum = 0;
    fetchList();
  }

  void loadData() {
    if (!hasNext) {
      controller.loadNoData();
    }
    currentNum += 1;
    fetchList();
  }

  void fetchAgree(int id) {
    EasyLoading.show();
    provider.takeCircleAgree(id).then((value) {
      if (value.isSuccess) {
        fetchList();
      }
      showToast(value.msg ?? '');
    }).whenComplete(() {
      EasyLoading.dismiss();
    });
  }

  void fetchList() {
    if (dataList.isEmpty) {
      EasyLoading.show();
    }
    provider.takeCircleList(currentNum).then((value) {
      if (value.isSuccess) {
        final list = value.data?.vos?.list ?? [];
        hasNext = value.data?.vos?.hasNext ?? false;
        if (currentNum == 0) {
          images.value = value.data?.images ?? [];
          dataList.value = list;
          controller.refreshCompleted();
        } else {
          dataList.value.addAll(list);
          if (hasNext) {
            controller.loadComplete();
          } else {
            controller.loadNoData();
          }
        }
      }
    }).catchError((_) {
      controller.refreshCompleted();
      controller.loadComplete();
    }).whenComplete(() {
      EasyLoading.dismiss();
    });
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    EasyLoading.dismiss();
    controller.dispose();
  }
}
